import os
import cv2
from skimage.metrics import structural_similarity
import imutils


def pic_same2(path1, path2):
    """
    判断两张图片是否相同
    :param path1:
    :param path2:
    :return:
    """
    threshold = 0.6
    imageA = cv2.imread(path1)
    imageB = cv2.imread(path2)
    grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
    (score, diff) = structural_similarity(grayA, grayB, full=True)
    diff = (diff * 255).astype("uint8")
    thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[1] if imutils.is_cv2() else cnts[0]
    for c in cnts:
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
    if score >= threshold:
        print("两张图片相似度符合要求,测试通过")
        return True
    else:
        print("两张图片相似度不符合要求,测试失败通过")
        cv2.imwrite("differ.png", imageA)
        return False


if __name__ == '__main__':
    pic_same2('2_2.png', '1_1.png')
